<?php
declare (strict_types = 1);

namespace app\middleware;

use think\facade\Cache;
use think\facade\Session;
class AdminPermission
{
    /**
     * 处理请求
     *
     * @param \think\Request $request
     * @param \Closure       $next
     * @return Response
     */
    public function handle($request, \Closure $next)
    {
        //超级管理员不需要验证
        $role_ids = Session::get('admin.role_ids');
        
        if (in_array(1,$role_ids)){
            return $next($request);
        }
        //验证权限
        $url = $request->baseUrl();
        //去'.html'
        if (substr($url, -5, 5) === '.html'){
            $url = substr($url, 0, -5);
        }
        $uid = Session::get('admin.id');
        $menus = Cache::get("admin:{$uid}:menu");
        $href = array_column($menus, 'href');

        if (!in_array($url, $href)) {
            if ($request->isAjax()) {
                return json(['code'=>999,'msg'=>'权限不足']);
            } else {
                exit('<div style="text-align: center;"><h1>权限不足</h1></div>');
            }
         }
        return $next($request);
    }
}
